using System;
using System.Collections;
using System.Collections.Generic;
using GameFramework.skill;
using GameFramework.skill.deployer;
using UnityEngine;

public class TowerCtl : MonoBehaviour
{
    //进入范围的敌人
    private List<Transform> enimys = new List<Transform>();
    //当前正在攻击的敌人
    private List<Transform> attackEnimys = new List<Transform>();

    public GameObject bulletPrefab;

    private SkillManager SkillManager;
    //此值应该从配置表获取
    private int atk_num = 1;
    //此值应该从配置表获取
    private int atk_interval = 1;//攻击间隔

    private float lastAtkTime;//上次攻击时间
    // Start is called before the first frame update
    void Start()
    {
        SkillManager = GetComponent<SkillManager>();
    }

    // Update is called once per frame
    void Update()
    {
        //检查攻击目标
        checkAtackTarget();
        //攻击
        attack();
    }

    private void attack()
    {
        if (attackEnimys.Count>0 && (Time.time - lastAtkTime) > atk_interval)
        {
            //检查能否放技能，能则调用技能管理的放技能功能，根据当前技能id
            Debug.Log("攻击");
            // var bullet = GameObject.Instantiate(bulletPrefab, transform.position, Quaternion.identity);
            // BulletCtl bulletCtl = bullet.GetComponent<BulletCtl>();
            // bulletCtl.target = attackEnimys[0].gameObject;
            //生成子弹，子弹预制体，子弹脚本 
            SkillManager.releaseSkill(1);
            lastAtkTime = Time.time;
        }


    }

    private void checkAtackTarget()
    {
        if (attackEnimys.Count < atk_num)
        {
            if(enimys.Count==0) return;
            for (int i = 0; i < atk_num; i++)
            {

                if (i == enimys.Count)
                {
                    break;
                }

                if (!attackEnimys.Contains(enimys[i]))
                {
                    attackEnimys.Add(enimys[i]);
                    Debug.Log("添加攻击目标");
                }
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {

        Transform enterTransform = other.gameObject.transform;
        if (enimys.Contains(enterTransform))
        {
            return;
        }
        enimys.Add(enterTransform);
        Debug.Log("攻击范围增加敌人！");
        //TODO 检查当前塔防的技能列表，给敌人添加相关的BUFF
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        Transform exitTransform = other.gameObject.transform;
        if (enimys.Contains(exitTransform))
        {
            enimys.Remove(exitTransform);
        }


        if (attackEnimys.Contains(exitTransform))
        {
            attackEnimys.Remove(exitTransform);
        }
        Debug.Log("退出攻击范围");
        //TODO 检查当前塔防的技能列表，给敌人移除相关的BUFF
    }
}
